const fs = require('fs');
// You'll need to define metadataPath - for example:
const path = require('path');
const metadataPath = path.join(__dirname, 'uploads', 'metadata.json');
const express = require('express');
const cors = require('cors');
const uploadRoutes = require('./routes/upload');
const http = require('http');

const app = express();

// MIDDLEWARE
app.use((req, res, next) => {
  // 生产环境CORS配置
  const allowedOrigins = [
    'http://47.103.78.83:5001',
    'http://47.103.78.83',
    'http://localhost:5001',
    'http://localhost:3000'
  ];
  
  const origin = req.headers.origin;
  if (allowedOrigins.includes(origin)) {
    res.header('Access-Control-Allow-Origin', origin);
  }
  
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  
  if (process.env.NODE_ENV !== 'production') {
    console.log(`Incoming ${req.method} request to ${req.url}`);
  }
  
  // 处理预检请求
  if (req.method === 'OPTIONS') {
    return res.status(200).end();
  }
  
  next();
});

app.use(cors({
  origin: function (origin, callback) {
    const allowedOrigins = [
      'http://47.103.78.83:5001',
      'http://47.103.78.83',
      'http://localhost:5001',
      'http://localhost:3000'
    ];
    // 允许没有origin的请求(比如移动端app)
    if (!origin) return callback(null, true);
    if (allowedOrigins.includes(origin)) {
      return callback(null, true);
    }
    return callback(null, false);
  },
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
}));

app.use(express.json());
app.use(express.static('public'));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// ROUTES
app.use('/api/upload', uploadRoutes);
app.use('/api/uploads', uploadRoutes);

// PUT endpoint to edit image descriptions
app.put('/api/edit-description', (req, res) => {
    const { filename, description } = req.body;
    
    console.log(`Received edit request for ${filename}: "${description}"`);
    console.log('Request body:', req.body);
    
    if (!filename || !description) {
        return res.status(400).json({ error: 'Filename and description are required' });
    }
    
    try {
        // Read the current metadata
        let metadata = {};
        if (fs.existsSync(metadataPath)) {
            const data = fs.readFileSync(metadataPath, 'utf8');
            metadata = JSON.parse(data);
        } else {
            console.log('Metadata file does not exist, creating new one');
            metadata = { images: [] };
        }
        
        // Ensure metadata has images array
        if (!metadata.images || !Array.isArray(metadata.images)) {
            console.log('Converting metadata to new format');
            metadata = { images: [] };
        }
        
        // Find and update the specific image
        let imageFound = false;
        console.log('Available filenames in metadata:', metadata.images.map(img => img.filename));
        console.log('Looking for filename:', filename);
        
        metadata.images = metadata.images.map(img => {
            if (img.filename === filename) {
                imageFound = true;
                console.log(`Found image ${filename}, updating description`);
                return {
                    ...img,
                    description: description,
                    updatedAt: new Date().toISOString()
                };
            }
            return img;
        });
        
        if (!imageFound) {
            console.log(`Image ${filename} not found in metadata`);
            console.log('Available images:', metadata.images.length);
            return res.status(404).json({ error: 'Image not found' });
        }
        
        // Write the updated metadata back to file
        fs.writeFileSync(metadataPath, JSON.stringify(metadata, null, 2));
        
        console.log(`Description updated successfully for ${filename}`);
        res.json({ 
            success: true, 
            message: 'Description updated successfully',
            filename: filename,
            newDescription: description
        });
        
    } catch (error) {
        console.error('Error updating description:', error);
        res.status(500).json({ error: 'Internal server error: ' + error.message });
    }
});

// ERROR HANDLER
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

// 启动服务器，处理端口被占用情况
const tryListen = (port) => {
  const server = http.createServer(app);

  server.listen(port, () => {
    console.log(`✅ Server running at http://localhost:${port}`);
  });

  server.on('error', (err) => {
    if (err.code === 'EADDRINUSE') {
      console.warn(`⚠️  Port ${port} is in use, trying port ${port + 1}...`);
      tryListen(port + 1);
    } else {
      console.error('❌ Server failed to start:', err);
    }
  });
};

const PORT = parseInt(process.env.PORT, 10) || 5001;
tryListen(PORT);